package com.jeehentor.generate.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeehentor.common.api.SystemCommonAPI;
import com.jeehentor.common.exception.HentorException;
import com.jeehentor.common.vo.OptionsVO;
import com.jeehentor.common.vo.Result;
import com.jeehentor.generate.dto.GenFormSaveDTO;
import com.jeehentor.generate.dto.GenModelDTO;
import com.jeehentor.generate.dto.SysGenFormQueryDTO;
import com.jeehentor.generate.entity.SysGenForm;
import com.jeehentor.generate.entity.SysGenModel;
import com.jeehentor.generate.entity.SysGenModelField;
import com.jeehentor.generate.entity.SysGenPage;
import com.jeehentor.generate.service.ISysGenFormService;
import com.jeehentor.generate.service.ISysGenModelFieldService;
import com.jeehentor.generate.service.ISysGenModelService;
import com.jeehentor.generate.service.ISysGenPageService;
import com.jeehentor.generate.vo.SysGenFormVO;
import com.jeehentor.utils.PageUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "表单配置主表")
@RestController
@RequiredArgsConstructor
@RequestMapping("/sysGenForm")
public class SysGenFormController {

    private final ISysGenFormService sysGenFormService;
    private final ISysGenModelService sysGenModelService;
    private final ISysGenModelFieldService sysGenModelFieldService;
    private final ISysGenPageService sysGenPageService;
    private final SystemCommonAPI systemCommonAPI;

    @Operation(summary = "保存")
    @PostMapping("/save")
    public Result<String> save(@RequestBody SysGenForm sysGenForm){
        sysGenFormService.save(sysGenForm);
        return Result.ok("保存成功");
    }

    @Operation(summary = "删除")
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody SysGenForm sysGenForm){
        LambdaQueryWrapper<SysGenPage> sysGenPageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysGenPageLambdaQueryWrapper.eq(SysGenPage::getFormId, sysGenForm.getId());
        List<SysGenPage> sysGenPageList = sysGenPageService.list(sysGenPageLambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(sysGenPageList)){
            return Result.error("表单配置下存在页面配置，请先删除页面配置");
        }
        sysGenFormService.removeById(sysGenForm);
        return Result.ok("删除成功");
    }


    @Operation(summary = "修改")
    @PostMapping("/update")
    public Result<String> update(@RequestBody SysGenForm sysGenForm){
        sysGenFormService.updateById(sysGenForm);
        return Result.ok("修改成功");
    }

    @Operation(summary = "分页查询")
    @PostMapping("/selectPage")
    public Result<IPage<SysGenFormVO>> selectPage(@RequestBody SysGenFormQueryDTO sysGenFormDTO){
        LambdaQueryWrapper<SysGenForm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(sysGenFormDTO.getFormName()), SysGenForm::getFormName, sysGenFormDTO.getFormName());
        Page<SysGenForm> page = sysGenFormService.page(sysGenFormDTO.getPage(), queryWrapper);
        Page<SysGenFormVO> sysGenFormVOPage = PageUtil.conversionVoPage(page, SysGenFormVO.class);
        if(CollectionUtil.isNotEmpty(sysGenFormVOPage.getRecords())){
            sysGenFormVOPage.getRecords().forEach(x->{
                x.setCreateByLabel(systemCommonAPI.getUserById(x.getCreateBy()).getUsername());
                x.setUpdateByLabel(systemCommonAPI.getUserById(x.getUpdateBy()).getUsername());
            });
        }
        return Result.OK(sysGenFormVOPage);
    }

    @PostMapping("/selectFormDetail")
    @Operation(summary = "查询表单配置")
    public Result<GenFormSaveDTO> selectFormDetail(@RequestBody GenFormSaveDTO dto) {
        GenFormSaveDTO genFormSaveDTO = sysGenFormService.selectFormDetail(dto);
        return Result.ok(genFormSaveDTO);
    }

    @PostMapping("/selectModelByFormId")
    @Operation(summary = "根据表单id查询模型字段")
    public Result<GenModelDTO> selectFormDetail(@RequestBody SysGenForm form) {
        SysGenForm sysGenForm = sysGenFormService.getById(form.getId());
        if(sysGenForm == null){
            throw new HentorException("表单不存在!");
        }
        if(StringUtils.isBlank(sysGenForm.getModelId())){
            throw new HentorException("表单未关联模型!");
        }
        GenModelDTO genModelDTO = new GenModelDTO();
        SysGenModel byId = sysGenModelService.getById(sysGenForm.getModelId());
        if(byId == null){
            throw new HentorException("模型不存在!");
        }
        BeanUtils.copyProperties(byId, genModelDTO);
        LambdaQueryWrapper<SysGenModelField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysGenModelField::getModelId, byId.getId());
        queryWrapper.orderByAsc(SysGenModelField::getSortOrder);
        List<SysGenModelField> list = sysGenModelFieldService.list(queryWrapper);
        genModelDTO.setFieldList(list);
        return Result.ok(genModelDTO);
    }

    @PostMapping("/getFormOptions")
    @Operation(summary = "模型下拉查询")
    public Result<List<OptionsVO>> getModelOptions(@RequestBody SysGenForm form) {
        LambdaQueryWrapper<SysGenForm> sysGenModelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysGenModelLambdaQueryWrapper.like(StringUtils.isNotBlank(form.getFormName()), SysGenForm::getFormName, form.getFormName());
        List<SysGenForm> list = sysGenFormService.list(sysGenModelLambdaQueryWrapper);
        ArrayList<OptionsVO> optionsVOS = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            list.forEach(x->{
                OptionsVO optionsVO = new OptionsVO();
                optionsVO.setLabel(x.getFormName());
                optionsVO.setValue(x.getId());
                optionsVOS.add(optionsVO);
            });
        }
        return Result.OK(optionsVOS);
    }


    @PostMapping("/saveOrUpdateForm")
    @Operation(summary = "保存或更新表单")
    public Result<String> saveOrUpdateForm(@RequestBody GenFormSaveDTO dto) {
        sysGenFormService.saveOrUpdateForm(dto);
        return Result.ok("保存成功");
    }

}
